package cn.edu.baiyunu.myapplication.ui.upload

import android.Manifest
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import cn.edu.baiyunu.myapplication.ui.components.BottomNavigationBar
import cn.edu.baiyunu.myapplication.ui.components.PatternDotsBackground
import cn.edu.baiyunu.myapplication.ui.components.UploadTopAppBar
import cn.edu.baiyunu.myapplication.ui.upload.components.CameraPreviewContent
import cn.edu.baiyunu.myapplication.ui.upload.components.PhotoPreviewContent
import cn.edu.baiyunu.myapplication.ui.upload.components.UploadContent

/**
 * 上传页面主屏幕组件
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UploadScreen(
    viewModel: UploadViewModel,
    onNavigateBack: () -> Unit,
    onNavigateToHome: () -> Unit,
    onNavigateToHistory: () -> Unit,
    onNavigateToEdit: () -> Unit,
    specType: String? = null
) {
    val context = LocalContext.current
    val snackbarHostState = remember { SnackbarHostState() }
    
    // 状态
    val screenState by viewModel.screenState.collectAsState()
    val selectedImageUri by viewModel.selectedImageUri.observeAsState()
    val selectedImageBitmap by viewModel.selectedImageBitmap.observeAsState()
    val statusMessage by viewModel.statusMessage.observeAsState()
    
    // 相机权限状态
    var hasCameraPermission by remember { mutableStateOf(false) }
    
    // 权限请求处理器
    val cameraPermissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        hasCameraPermission = isGranted
        if (isGranted) {
            viewModel.setScreenState(UploadViewModel.UploadScreenState.CAMERA)
        } else {
            viewModel.setStatusMessage("需要相机权限才能拍照")
        }
    }
    
    // 文件选择处理器
    val galleryLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let { viewModel.setSelectedImageUri(it) }
    }
    
    // 如果指定了规格类型，则设置到ViewModel
    LaunchedEffect(specType) {
        specType?.let { viewModel.setSpecType(it) }
    }
    
    // 状态消息效果
    LaunchedEffect(statusMessage) {
        statusMessage?.let {
            snackbarHostState.showSnackbar(it)
        }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        // 添加图案背景
        PatternDotsBackground()
        
        // 主要内容
        Scaffold(
            topBar = {
                UploadTopAppBar(
                    onNavigateBack = onNavigateBack,
                    showBackButton = true,
                    title = "上传照片"
                )
            },
            bottomBar = {
                BottomNavigationBar(
                    currentRoute = "upload",
                    onNavigateToRoute = { route ->
                        when (route) {
                            "home" -> onNavigateToHome()
                            "upload" -> { /* 已在上传页面 */ }
                            "history" -> onNavigateToHistory()
                        }
                    }
                )
            },
            snackbarHost = { SnackbarHost(snackbarHostState) },
            containerColor = Color.Transparent
        ) { innerPadding ->
            // 根据当前状态显示不同内容
            when (screenState) {
                UploadViewModel.UploadScreenState.UPLOAD -> {
                    UploadContent(
                        onSelectPhotoClick = { galleryLauncher.launch("image/*") },
                        onCameraClick = { 
                            cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
                        },
                        onFileDrop = { galleryLauncher.launch("image/*") },
                        modifier = Modifier.padding(innerPadding)
                    )
                }
                
                UploadViewModel.UploadScreenState.CAMERA -> {
                    CameraPreviewContent(
                        onImageCaptured = { bitmap ->
                            viewModel.setSelectedImageBitmap(bitmap)
                        },
                        onCancel = {
                            viewModel.setScreenState(UploadViewModel.UploadScreenState.UPLOAD)
                        },
                        modifier = Modifier.padding(innerPadding)
                    )
                }
                
                UploadViewModel.UploadScreenState.PREVIEW -> {
                    PhotoPreviewContent(
                        imageUri = selectedImageUri,
                        imageBitmap = selectedImageBitmap,
                        onDeleteClick = { viewModel.clearSelectedImage() },
                        onReUploadClick = { 
                            viewModel.clearSelectedImage() 
                            viewModel.setScreenState(UploadViewModel.UploadScreenState.UPLOAD)
                        },
                        onUsePhotoClick = onNavigateToEdit,
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
    }
} 